﻿using CYQ.Data;
using CYQ.Data.Table;
using CYQ.Data.Tool;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace DBCheck
{
    public partial class Form_Check : Form
    {
        string sqlitestr = "Data Source=dbinfo.db;failifmissing=false;";
        public Form_Check()
        {
            InitializeComponent();
            AppConfig.Cache.IsAutoCache = false;
        }


        private void OutMsg(string v)
        {
            txt_log.AppendText(v + "\r\n");
        }

        private void btn_check_Click(object sender, EventArgs e)
        {
            CYQ.Data.Cache.CacheManage.LocalInstance.Clear();
            string dbname = cb_dbinfo.Text;//模板数据库名
            string sqlconnstr = txt_conn.Text;
            bool result = DBTool.TestConn(sqlconnstr);
            if (!result)
            {
                OutMsg("连接数据库失败：" + sqlconnstr);
                return;
            }
            MDataTable dt;
            using (MAction action = new MAction(TableNames.tableinfo, sqlitestr))
            {
                dt = action.Select(string.Format("dbname='{0}'", dbname));
            }
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (MDataRow item in dt.Rows)
                {
                    string tbname = item["tablename"].Value.ToString();
                    OutMsg(string.Format("--------------{0}---------------", tbname));
                    MDataTable dtCols;
                    using (MAction action = new MAction(TableNames.Colinfo, sqlitestr))
                    {//读取所有字段
                        dtCols = action.Select(string.Format(" dbname='{0}' and tablename='{1}' ", dbname, tbname));
                    }
                    MDataColumn newMdc = new MDataColumn();
                    foreach (var itemcol in dtCols.Rows)
                    {
                        string scol = itemcol["columnName"].Value.ToString();
                        string type = itemcol["sqlType"].Value.ToString();
                        int MaxSize = int.Parse(itemcol["MaxSize"].Value.ToString());
                        bool isCanNull = (bool)itemcol["isCanNull"].Value;
                        bool isAutoIncrement = (bool)itemcol["isAutoIncrement"].Value;
                        bool isPrimaryKey = (bool)itemcol["isPrimaryKey"].Value;
                        object defaultValue = itemcol["defaultValue"].Value;

                        newMdc.Add(scol, (SqlDbType)Enum.Parse(typeof(SqlDbType), type), isAutoIncrement, isCanNull, MaxSize, isPrimaryKey, defaultValue);
                    }
                    if (DBTool.ExistsTable(tbname, sqlconnstr))
                    {//检查字段是否完整
                        MDataColumn mdc = DBTool.GetColumns(tbname, sqlconnstr);
                        //MDataColumn newMdc = new MDataColumn();
                        foreach (var itemcol in dtCols.Rows)
                        {
                            string scol = itemcol["columnName"].Value.ToString();
                            string type = itemcol["sqlType"].Value.ToString();
                            //int MaxSize = int.Parse(itemcol["MaxSize"].Value.ToString());
                            //bool isCanNull = (bool)itemcol["isCanNull"].Value;
                            //bool isAutoIncrement = (bool)itemcol["isAutoIncrement"].Value;
                            //bool isPrimaryKey = (bool)itemcol["isPrimaryKey"].Value;
                            //object defaultValue = itemcol["defaultValue"].Value;
                            //newMdc.Add(scol, (SqlDbType)Enum.Parse(typeof(SqlDbType), type), isAutoIncrement, isCanNull, MaxSize, isPrimaryKey, defaultValue);
                            if (!mdc.Contains(scol))
                            {
                                //OutMsg(string.Format("--缺少字段：{0} 类型：{1}", scol, type));
                                newMdc[scol].AlterOp = AlterOp.AddOrModify;
                            }
                        }
                        string sql = DBTool.GetAlterTableSql(tbname, newMdc, sqlconnstr);
                        if (sql != "")
                            OutMsg(sql);
                    }
                    else
                    {//需要创建表                        
                        string sql = DBTool.GetCreateTableSql(tbname, newMdc, DalType.MsSql, "00");
                        OutMsg(sql);
                    }
                    OutMsg(string.Format("------表：{0} 检测完成--------", tbname));
                }
            }
            else
            {
                OutMsg(string.Format("没有模板:（{0}）信息", cb_dbinfo.Text));
            }

        }

        private void Menu_Edit_Click(object sender, EventArgs e)
        {
            using (Form_NewestDB frm = new Form_NewestDB())
            {
                frm.ShowDialog();
            }
            Loaddbinfo();
        }

        private void Form_Check_Load(object sender, EventArgs e)
        {
            Loaddbinfo();
        }
        private void Loaddbinfo()
        {
            using (MAction action = new MAction(TableNames.dbinfo, sqlitestr))
            {
                var dt = action.Select();
                cb_dbinfo.DisplayMember = "dbname";
                cb_dbinfo.ValueMember = "update";
                cb_dbinfo.DataSource = dt.ToDataTable();
                cb_dbinfo.Text = "";
            }
        }
    }
}
